//
//  JokeViewController.m
//  BeanTrip
//
//  Created by houlei on 15/7/8.
//  Copyright (c) 2015年 PandaGroup. All rights reserved.
//

#import "JokeViewController.h"
#import "JokeCollectionViewCell.h"
#import "HTTPTool.h"
#import "JokeModel.h"
#import "MJRefresh.h"
#import "UMSocial.h"

#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)
@interface JokeViewController ()

@end

@implementation JokeViewController


- (void)dealloc
{
    [_HUD release];
    [_maxtime release];
    [_jokeArray release];
    [_collectionView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"摘自不得姐";
    
    self.view.backgroundColor = [UIColor yellowColor];
    //刷新所需变量
    self.maxtime = @"";
    self.jokeArray = [NSMutableArray array];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49) collectionViewLayout:flowLayout];
    //设置item的大小
    flowLayout.itemSize = CGSizeMake(WIDTH - 20, HEIGHT);
    //设置每行item的间隔
    flowLayout.minimumLineSpacing = 20;
    //设置每列item的间隔
    flowLayout.minimumInteritemSpacing = 10;
    //设置滚动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置item各边的距离(上左下右)
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    //注册cell
    [self.collectionView registerClass:[JokeCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    //刷新
    [self addHeader];
    [self addFooter];
    
    //添加菊花
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"加载中";
    [self.HUD show:YES];
    //请求网络数据
    [self getData:@""];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.jokeArray.count;
}
//布局item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //直接从系统的重用池中取item
    JokeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.jokeM = [self.jokeArray objectAtIndex:indexPath.row];
    //cell动画
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];


    return cell;
}
//分享
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55a3a50767e58eded90035da"
                                      shareText:[[self.jokeArray objectAtIndex:indexPath.row] text]
                                     shareImage:nil
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToTencent,nil]
                                       delegate:nil];
}

- (void)getData:(NSString *)maxtime
{
    NSString *url = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=73524B41-B2E2-47A7-B7FD-F20ADEFBE5DA&c=data&client=iphone&from=ios&jbk=0&mac=&market=&maxtime=%@&openudid=4c65d5f4fc3ff9b36a159d32c4a1dd434041ab3f&page=0&per=20&sub_flag=1&type=29&udid=&ver=3.6",maxtime];
    [HTTPTool get:url body:nil httpResult:JSON success:^(id result) {
        if (self.isUpLoading == NO) {
            [self.jokeArray removeAllObjects];
        }
        NSMutableDictionary *dic = result;
        NSMutableDictionary *dic1 = dic[@"info"];
        self.maxtime = dic1[@"maxtime"];
        NSMutableArray *array = dic[@"list"];
        for (NSMutableDictionary *dic2 in array) {
            JokeModel *jokeM = [[JokeModel alloc] init];
            [jokeM initWithDic:dic2];
            [self.jokeArray addObject:jokeM];
        }
        [self.collectionView headerEndRefreshing];
        [self.collectionView footerEndRefreshing];
        [self.collectionView reloadData];
        [self.HUD removeFromSuperview];
        
    } failure:^(NSError *error) {
        
        
    }];
}
//刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block JokeViewController *vc = self;
    
    // 添加下拉刷新头部控件
    [self.collectionView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.maxtime = @"";
        vc.isUpLoading = NO;//标记为下拉操作
        [vc getData:vc.maxtime];//重新请求数据
        
    }];

}
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block JokeViewController *vc = self;
    // 添加上拉刷新尾部控件
    [self.collectionView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.isUpLoading = YES;//标记为上拉操作
        [vc getData:vc.maxtime];//请求更多数据
        
    }];

}
//item的自适应
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    JokeModel *jokeM = [self.jokeArray objectAtIndex:indexPath.row];
    CGFloat height = [JokeCollectionViewCell heightForContent:jokeM.text];
    self.sizeForItem = CGSizeMake(WIDTH - 20, height+10);
    return self.sizeForItem;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
